﻿using Kw.Combinatorics;

using NxERP.Bll;

using System.Collections.Generic;
using System.Data;

namespace LengthAiCalculate
{
    public class Ai

    {
        private SqlHelper sqlHelper;

        private DataTable scDt;

        private DataTable jhDt;

        private DataTable cutTable;

        private List<string> scList = new List<string>();

        private List<string> jhList = new List<string>();

        private const int Dog = 6;//全局Dog控制

        private int addNum = 0;

        private int baseOpDog = 0;

        private int C1Dog = 0;

        private int C2Dog = 0;

        private string mID;

        private double cutLength = 3;

        //private string jhOrderBy = "";
        /// <summary>
        /// </summary>
        /// <param name="sqlHelper"> </param>
        /// <param name="mid">       </param>
        /// <param name="cutLength"> </param>
        /// <param name="isPlan">    是否正在生产 </param>
        public Ai(SqlHelper sqlHelper, string mid, double cutLength, bool isPlan)
        {
            this.sqlHelper = sqlHelper;
            this.mID = mid;
            this.cutLength = cutLength;
            if (!isPlan)
            {
                sqlHelper.ExcuteSql($"DELETE FROM [PM.AiResult] WHERE mid='{mid}' AND (isUserAdd=0 OR isUserAdd IS NULL);UPDATE [PM.AiJh] SET num=numBack- ISNULL(cutNum, 0) WHERE mId='{mid}';UPDATE [PM.AiSc] SET num=numBack-ISNULL(realNum, 0) WHERE mID='{mid}';DELETE [PM.AiJh] WHERE mId='{mid}' AND numBack=0");
            }
            else
            {
                sqlHelper.ExcuteSql($"DELETE FROM [PM.AiResult] WHERE isUserAdd=0 AND mid='{mid}';UPDATE [PM.AiJh] SET num=numBack- ISNULL(cutNum, 0) WHERE mId='{mid}';UPDATE [PM.AiSc] SET num=numBack-ISNULL(realNum, 0) WHERE mID='{mid}'");
            }
            Init();
            UserAddC(mid);
        }

        /// <summary>
        /// 非锯切表中单根生产完初始化数据
        /// </summary>
        public void MInit()
        {
            sqlHelper.ExcuteSql($"DELETE FROM [PM.AiResult] WHERE isUserAdd=0 AND mid='{mID}';UPDATE [PM.AiJh] SET num=numBack-realNum WHERE mId='{mID}';UPDATE [PM.AiSc] SET num=numBack-realNum WHERE mID='{mID}'");
        }

        public void UserAddC(string mid)
        {
            DataTable dt = sqlHelper.GetDataTableFromSql($"SELECT cutGroup,num,mLength FROM [PM.AiResult] WHERE isUserAdd=1 AND mID='{mid}'");
            if (dt.Rows.Count > 0)
            {
                List<string> sql = new List<string>();
                string op = "-";
                foreach (DataRow row in dt.Rows)
                {
                    string mLength = row["mLength"].ToString().Trim();
                    string[] cut = row["cutGroup"].ToString().Split('=')[1].Split('+');
                    int.TryParse(row["num"].ToString(), out var num);
                    foreach (var item in cut)
                    {
                        string[] m = item.Split('*');
                        sql.Add($"UPDATE [PM.AiJh] SET num=num{op}{m[1]}*{num} WHERE mId='{mid}'AND lg={m[0]}");
                    }
                    sql.Add($"UPDATE [PM.AiSc] SET num=num{op}{num} WHERE mID='{mid}' AND lg={mLength}");
                }
                sqlHelper.ExcuteSql(sql);
            }
        }

        public void UserAddDel(string mid, string id)
        {
            DataTable dt = sqlHelper.GetDataTableFromSql($"SELECT cutGroup,num,mLength FROM [PM.AiResult] WHERE id={id}");
            if (dt.Rows.Count > 0)
            {
                List<string> sql = new List<string>();
                string op = "+";
                foreach (DataRow row in dt.Rows)
                {
                    string mLength = row["mLength"].ToString().Trim();
                    string[] cut = row["cutGroup"].ToString().Split('=')[1].Split('+');
                    int.TryParse(row["num"].ToString(), out var num);
                    foreach (var item in cut)
                    {
                        string[] m = item.Split('*');
                        sql.Add($"UPDATE [PM.AiJh] SET num=num{op}{m[1]}*{num} WHERE mId='{mid}'AND lg={m[0]}");
                    }
                    sql.Add($"UPDATE [PM.AiSc] SET num=num{op}{num} WHERE mID='{mid}' AND lg={mLength}");
                }
                sqlHelper.ExcuteSql(sql);
            }
        }

        /// <summary>
        /// 更新组合优先级
        /// </summary>
        /// <param name="sqlHelper"> </param>
        private void UP(SqlHelper sqlHelper)
        {
            List<string> ipsql = new List<string>();
            foreach (DataRow item in jhDt.Rows)
            {
                string id = item["id"].ToString();
                string lg = item["lg"].ToString();
                int cutGroupNum = sqlHelper.GetCount("[v_LA_CutTable]", $@"mLength IN ({string.Join(",", scList)}) AND mainLength IN ({string.Join(",", jhList)}) AND (length IN ({string.Join(",", jhList)}) OR length IS NULL) AND mainLength={lg}");
                int mNum = sqlHelper.GetDistinctCount("[v_LA_CutTable]", "mLength", $@"mLength IN ({string.Join(",", scList)}) AND mainLength IN ({string.Join(",", jhList)}) AND (length IN ({string.Join(",", jhList)}) OR length IS NULL) AND mainLength={lg}");
                ipsql.Add($"UPDATE [PM.AiJh] SET cutGroupNum={cutGroupNum},mNum={mNum} WHERE id={id}");
            }
            sqlHelper.ExcuteSql(string.Join(";", ipsql));
        }

        /// <summary>
        /// 套材基本计算前初始化
        /// </summary>
        private void Init()
        {
            scList.Clear();
            jhList.Clear();
            scDt = sqlHelper.GetDataTableFromSql($"SELECT * FROM [PM.AiSc] WHERE mID='{mID}' AND num>0");
            jhDt = sqlHelper.GetDataTableFromSql($"SELECT * FROM [PM.AiJh] WHERE mID='{mID}' AND num>{addNum}");
            foreach (DataRow item in scDt.Rows)
            {
                scList.Add(item["lg"].ToString());
            }
            foreach (DataRow item in jhDt.Rows)
            {
                jhList.Add(item["lg"].ToString());
            }
            if (scList.Count > 0 && jhList.Count > 0)
            {
                UP(sqlHelper);
                cutTable = sqlHelper.GetDataTableFromSql($@"SELECT cutGroup,cutGuid, mLength, cutLenthItemId, length, num, mainLength, mainNum, mKey FROM [v_LA_CutTable] WHERE mLength IN ({string.Join(",", scList)}) AND mainLength IN ({string.Join(",", jhList)}) AND (length IN ({string.Join(",", jhList)}) OR length IS NULL)");
            }
        }

        /// <summary>
        /// 套材基本计算
        /// </summary>
        public void BaseOp()
        {
            baseOpDog++;
            Init();
            DataTable dt = sqlHelper.GetDataTableFromSql($@"SELECT id,lg,num,isdel,cutGroupNum,mNum FROM [PM.AiJh] WHERE mID='{mID}' AND num>{addNum} AND cutGroupNum>0 ORDER BY cutGroupNum asc,mNum desc");
            foreach (DataRow row in dt.Rows)
            {
                string lg = row["lg"].ToString().Trim();
                int count = sqlHelper.GetCount("[v_LA_CutTable]", $"mLength IN ({string.Join(", ", scList)}) AND mainLength={row["lg"]}");
                if (count == 0)
                {
                    continue;
                }
                cutTable = sqlHelper.GetDataTableFromSql($@"SELECT cutGroup, cutGuid, mLength, cutLenthItemId, length, num, mainLength, mainNum, mKey FROM [v_LA_CutTable] WHERE mLength IN ({string.Join(",", scList)}) AND (length IN ({string.Join(",", jhList)}) OR length IS NULL) AND mainLength = {lg} ORDER BY mainNum DESC,length DESC");
                foreach (DataRow item in cutTable.Rows)
                {
                    string mLength = item["mLength"].ToString();
                    string cutGroup = item["cutGroup"].ToString();

                    string mainLength = item["mainLength"].ToString();
                    int mainNum = int.Parse(item["mainNum"].ToString());
                    if (mainNum < addNum) continue;
                    var 辅定尺支数 = 0;
                    int num = 0;
                    string length;
                    if (item["length"].ToString().Trim() != "")
                    {
                        length = item["length"].ToString();
                        num = int.Parse(item["num"].ToString());
                        int.TryParse(sqlHelper.GetColumnValue("[PM.AiJh]", "num", $"mID='{mID}' AND num>{addNum} and lg={length}"), out 辅定尺支数);
                    }
                    else
                    {
                        length = "0";
                    }
                    int.TryParse(sqlHelper.GetColumnValue("[PM.AiJh]", "num", $"mID='{mID}' AND num>{addNum} and lg={mainLength}"), out var 主定尺支数);
                    if (主定尺支数 <= 0) continue;
                    int 主定尺大料数 = 主定尺支数 / mainNum;
                    int 主定尺大料数余数 = 主定尺支数 % mainNum;
                    if (主定尺大料数余数 > 0)
                    {
                        主定尺大料数 += 1;
                    }
                    int 辅定尺大料数 = 0;
                    int 辅定尺大料数余数 = 0;
                    if (num < addNum) continue;
                    if (num > 0)
                    {
                        辅定尺大料数 = 辅定尺支数 / num;
                        辅定尺大料数余数 = 辅定尺支数 % num;
                    }
                    if (辅定尺大料数余数 > 0)
                    {
                        辅定尺大料数 += 1;
                    }

                    int 实际大料消耗支数 = 主定尺大料数;
                    if (主定尺大料数 > 辅定尺大料数 && num > 0)
                    {
                        实际大料消耗支数 = 辅定尺大料数;
                    }
                    int.TryParse(sqlHelper.GetColumnValue("[PM.AiSc]", "num", $"mID='{mID}' AND num>0 and lg={mLength}"), out var 原料支数);

                    if (实际大料消耗支数 > 原料支数)
                    {
                        实际大料消耗支数 = 原料支数;
                    }
                    if (实际大料消耗支数 <= 0) continue;
                    List<string> sqlList = new List<string>();
                    sqlList.Add($"UPDATE [PM.AiJh] SET num=num-{实际大料消耗支数 * mainNum} WHERE mID='{mID}' AND lg={mainLength}");
                    sqlList.Add($"UPDATE [PM.AiJh] SET num=num-{实际大料消耗支数 * num} WHERE mID='{mID}' AND lg={length}");
                    sqlList.Add($"UPDATE [PM.AiSc] SET num=num-{实际大料消耗支数} WHERE mID='{mID}' AND lg={mLength}");
                    sqlList.Add($"IF EXISTS (SELECT * FROM [PM.AiResult] WHERE mID = '{mID}' AND cutGroup = '{cutGroup}' AND isUserAdd=0) UPDATE [PM.AiResult] SET num = num + {实际大料消耗支数},numBack=numBack+{实际大料消耗支数} WHERE mID = '{mID}' AND cutGroup = '{cutGroup}' AND isUserAdd=0 ELSE INSERT INTO [PM.AiResult] (cutGroup,num,mLength,twoCutNum,opType,mid,isAbandon,isUserAdd,numBack) VALUES ('{cutGroup}',{实际大料消耗支数},{mLength},0,'op','{mID}',0,0,{实际大料消耗支数})");
                    sqlHelper.ExcuteSql(sqlList);
                }
            }
            int i = sqlHelper.GetCount("[PM.AiJh]", $"mID='{mID}' AND num>{addNum}");
            if (i > 0 && baseOpDog <= Dog)
            {
                BaseOp();
            }
        }

        /// <summary>
        /// 基本计算完成后，保成材率算法
        /// </summary>
        public void C1()
        {
            C1Dog++;
            jhDt = sqlHelper.GetDataTableFromSql($"SELECT * FROM [PM.AiJh] WHERE mID='{mID}' AND num>0 ORDER BY lg DESC,num DESC");
            scDt = sqlHelper.GetDataTableFromSql($"SELECT * FROM [PM.AiSc] WHERE mID='{mID}'AND num>0");
            if (scList.Count > 0 && jhList.Count > 0 && C1Dog <= Dog)
            {
                foreach (DataRow item in jhDt.Rows)
                {
                    if (scDt.Rows.Count == 0)
                    {
                        break;
                    }
                    List<string> sql = new List<string>();
                    string mainLenght = item["lg"].ToString().Trim();
                    cutTable = sqlHelper.GetDataTableFromSql($@"SELECT TOP(1) cutGroup,cutGuid,mLength,cutLenthItemId,length,num,mainLength,mainNum,mKey FROM [v_LA_CutTable] WHERE mLength IN ({string.Join(",", scList)}) AND mainLength = {mainLenght} ORDER BY mainNum DESC,[length] DESC");
                    if (cutTable.Rows.Count > 0)
                    {
                        int mainNum = int.Parse(cutTable.Rows[0]["mainNum"].ToString());
                        string mLength = cutTable.Rows[0]["mLength"].ToString();
                        string length = cutTable.Rows[0]["length"].ToString();
                        string cutGroup = cutTable.Rows[0]["cutGroup"].ToString();
                        double _length = 0;
                        int num = 0;
                        if (length.Length > 0)
                        {
                            num = int.Parse(cutTable.Rows[0]["num"].ToString());
                            _length = double.Parse(length);
                        }
                        int jhNum = int.Parse(item["num"].ToString());
                        int zs = jhNum / mainNum;
                        int ys = jhNum % mainNum;
                        if (ys > 0)
                        {
                            zs += 1;
                        }
                        int.TryParse(sqlHelper.GetColumnValue("[PM.AiSc]", "num", $"mID='{mID}' AND num>0 and lg={mLength}"), out var 原料支数);
                        if (原料支数 < zs)
                        {
                            zs = 原料支数;
                        }
                        sql.Add($"UPDATE [PM.AiJh] SET num=num-{zs * mainNum} WHERE mID='{mID}' AND lg={mainLenght}");
                        sql.Add($"UPDATE [PM.AiSc] SET num=num-{zs} WHERE mID='{mID}' AND lg={mLength}");
                        if (num > 0)
                        {
                            double fdcNum = zs * num;
                            double 分割数量 = 0;
                            DataTable temp = sqlHelper.GetDataTableFromSql($"SELECT  * FROM [PM.AiJh] WHERE mID='{mID}' AND num>0 AND lg<>{mainLenght} AND lg<>{length}");
                            if (temp.Rows.Count > 0)
                            {
                                foreach (DataRow row in temp.Rows)
                                {
                                    double _lg = double.Parse(row["lg"].ToString());
                                    int _num = int.Parse(row["num"].ToString());
                                    double k = _length % _lg;
                                    if (k == 0)
                                    {
                                        分割数量 = _num / (_length / _lg);
                                        double 分割余数 = _num % (_length / _lg);
                                        if (分割余数 > 0)
                                        {
                                            分割数量 += 1;
                                        }
                                        sql.Add($"UPDATE [PM.AiJh] SET num=num-{分割数量 * (_length / _lg)} WHERE mID='{mID}' AND lg={_lg}");
                                        fdcNum -= 分割数量;
                                        break;
                                    }
                                }
                            }
                            sql.Add($@"IF EXISTS (SELECT * FROM [PM.AiJh] WHERE mID='{mID}' AND lg={length}) UPDATE [PM.AiJh] SET num=num-{fdcNum} WHERE mID='{mID}' AND lg={length} ELSE INSERT INTO [PM.AiJh] (lg,num,isdel,cutGroupNum, mNum,mID,realNum,numBack) VALUES ({length},-{fdcNum},0,NULL,NULL,'{mID}',0,0)");
                            sql.Add($@"IF EXISTS (SELECT * FROM [PM.AiResult] WHERE mID = '{mID}' AND cutGroup = '{cutGroup}' AND isUserAdd=0) UPDATE [PM.AiResult] SET num = num + {zs},twoCutNum=twoCutNum+{分割数量},numBack=numBack+{zs} WHERE mID = '{mID}' AND cutGroup = '{cutGroup}' AND isUserAdd=0 ELSE INSERT INTO [PM.AiResult] (cutGroup,num,mLength,twoCutNum,opType,mID,isAbandon,isUserAdd,numBack) VALUES ('{cutGroup}',{zs},{mLength},{分割数量},'c1','{mID}',0,0,{zs})");
                        }
                        else
                        {
                            sql.Add($@"IF EXISTS (SELECT * FROM [PM.AiResult] WHERE mID = '{mID}' AND cutGroup = '{cutGroup}' AND isUserAdd=0) UPDATE [PM.AiResult] SET num = num + {zs},numBack=numBack+{zs} WHERE mID = '{mID}' AND cutGroup = '{cutGroup}' AND isUserAdd=0 ELSE INSERT INTO [PM.AiResult] (cutGroup,num,mLength,twoCutNum,opType,mID,isAbandon,isUserAdd,numBack) VALUES ('{cutGroup}',{zs},{mLength},0,'c1','{mID}',0,0,{zs})");
                        }
                        sqlHelper.ExcuteSql(string.Join(";", sql));
                        jhDt = sqlHelper.GetDataTableFromSql($"SELECT * FROM [PM.AiJh] WHERE mID='{mID}' AND num>0 ORDER BY num DESC,lg DESC");
                        scDt = sqlHelper.GetDataTableFromSql($"SELECT * FROM [PM.AiSc] WHERE mID='{mID}' AND num>0");
                        scList.Clear();
                        jhList.Clear();
                        foreach (DataRow item1 in scDt.Rows)
                        {
                            scList.Add(item1["lg"].ToString());
                        }
                        foreach (DataRow item2 in jhDt.Rows)
                        {
                            jhList.Add(item2["lg"].ToString());
                        }
                        if (scList.Count > 0 && jhList.Count > 0)
                        {
                            cutTable = sqlHelper.GetDataTableFromSql($@"SELECT TOP (1) cutGroup, cutGuid, mLength, cutLenthItemId, length, num, mainLength, mainNum, mKey FROM [v_LA_CutTable] WHERE mLength IN ({string.Join(",", scList)}) AND mainLength = {mainLenght} ORDER BY mainNum DESC, [length] DESC");
                        }
                    }
                }
                C1();
            }
        }

        /// <summary>
        /// 基本计算完成后，保计划完成率算法
        /// </summary>
        public void C2()
        {
            C2Dog++;
            jhDt = sqlHelper.GetDataTableFromSql($"SELECT * FROM [PM.AiJh] WHERE mID='{mID}' AND num>0 ORDER BY lg DESC,num DESC");
            scDt = sqlHelper.GetDataTableFromSql($"SELECT * FROM [PM.AiSc] WHERE mID='{mID}' AND num>0 ORDER BY lg ASC");
            if (jhDt.Rows.Count > 0 && scDt.Rows.Count > 0 && C2Dog <= Dog)
            {
                foreach (DataRow item in jhDt.Rows)
                {
                    if (C2Dog >= Dog)
                    {
                        break;
                    }
                    if (scDt.Rows.Count == 0)
                    {
                        break;
                    }
                    List<string> sql = new List<string>();
                    string mainLenght = item["lg"].ToString().Trim();
                    int mainNum = int.Parse(item["num"].ToString().Trim());
                    string mLength = scDt.Rows[0]["lg"].ToString();
                    string mNum = scDt.Rows[0]["num"].ToString();
                    int _mNum = int.Parse(mNum);
                    double _mainLenght = double.Parse(mainLenght);
                    double _mLength = double.Parse(mLength);
                    int s = (int)(_mLength / _mainLenght);
                    int zs = mainNum / s;
                    int ys = mainNum % s;
                    if (ys > 0)
                    {
                        zs += 1;
                    }
                    if (zs > _mNum)
                    {
                        zs = _mNum;
                    }
                    double syLength = _mLength - _mainLenght * s;
                    int isAbandon = 1;
                    string cut = "";
                    bool flag = true;
                    if (syLength <= cutLength)
                    {
                        if (syLength > 0)
                        {
                            cut = mLength + "=" + mainLenght + "*" + s.ToString() + "+" + syLength.ToString() + "*1";
                        }
                        else
                        {
                            cut = mLength + "=" + mainLenght + "*" + s.ToString();
                            isAbandon = 0;
                        }
                        sql.Add($"IF EXISTS (SELECT * FROM [PM.AiResult] WHERE mID = '{mID}' AND cutGroup = '{cut}' AND isUserAdd=0) UPDATE [PM.AiResult] SET num = num + {zs},numBack=numBack+{zs},isAbandon=isAbandon+{isAbandon} WHERE mID = '{mID}' AND cutGroup = '{cut}' AND isUserAdd=0 ELSE INSERT INTO [PM.AiResult] (cutGroup,num,mLength,twoCutNum,opType,mID,isAbandon,isUserAdd,numBack) VALUES ('{cut}',{zs},{mLength},0,'c2','{mID}',{isAbandon},0,{zs})");
                        sql.Add($"UPDATE [PM.AiSc] SET num=num-{zs} WHERE mID='{mID}' AND lg={mLength}");
                        sql.Add($"UPDATE [PM.AiJh] SET num=num-{zs * s} WHERE mID='{mID}' AND lg={mainLenght}");
                    }
                    else if (syLength >= 6)
                    {
                        isAbandon = 0;
                        cut = mLength + "=" + mainLenght + "*" + s.ToString() + "+" + syLength.ToString() + "*1";

                        sql.Add($"IF EXISTS (SELECT * FROM [PM.AiResult] WHERE mID = '{mID}' AND cutGroup = '{cut}' AND isUserAdd=0) UPDATE [PM.AiResult] SET num = num + {zs},numBack=numBack+{zs} WHERE mID = '{mID}' AND cutGroup = '{cut}' AND isUserAdd=0 ELSE INSERT INTO [PM.AiResult] (cutGroup,num,mLength,twoCutNum,opType,mID,isAbandon,isUserAdd,,numBack) VALUES ('{cut}',{zs},{mLength},0,'c2','{mID}',{isAbandon},0,{zs})");

                        sql.Add($"UPDATE [PM.AiSc] SET num=num-{zs} WHERE mID='{mID}' AND lg={mLength}");

                        sql.Add($"UPDATE [PM.AiJh] SET num=num-{zs * s} WHERE mID='{mID}' AND lg={mainLenght}");

                        sql.Add($@"IF EXISTS (SELECT * FROM [PM.AiJh] WHERE mId='{mID}' AND lg={syLength}) UPDATE [PM.AiJh] SET num=num-{zs} WHERE mId='{mID}' AND lg={syLength} ELSE INSERT INTO [PM.AiJh] (lg,num,isdel,cutGroupNum,mNum,mId,numBack,realNum) VALUES ({syLength},-{zs}, 0, NULL, NULL,'{mID}',0,0)");
                    }
                    else
                    {
                        C2Dog++;
                        flag = false;
                    }
                    if (flag)
                    {
                        sqlHelper.ExcuteSql(sql);
                        jhDt = sqlHelper.GetDataTableFromSql($"SELECT * FROM [PM.AiJh] WHERE mID='{mID}' AND num>0 ORDER BY num DESC,lg DESC");
                        scDt = sqlHelper.GetDataTableFromSql($"SELECT * FROM [PM.AiSc] WHERE mID='{mID}' AND num>0 ORDER BY lg ASC");
                    }
                }
                C2();
            }
        }

        /// <summary>
        /// 剩余坯料生产
        /// </summary>
        public void C3()
        {
            scDt = sqlHelper.GetDataTableFromSql($"SELECT lg,num FROM [PM.AiSc] WHERE mID='{mID}' AND num>0 ORDER BY lg ASC");
            if (scDt.Rows.Count > 0)
            {
                foreach (DataRow item in scDt.Rows)
                {
                    string mLength = item["lg"].ToString();
                    string mNum = item["num"].ToString();
                    DataTable dt = sqlHelper.GetDataTableFromSql($"SELECT TOP(1) id,cutGroup,LEN(cutGroup)- LEN(REPLACE(cutGroup,'*','')) px FROM [PM.AiResult] WHERE isAbandon=0 AND mLength = {mLength} ORDER BY px ASC,num DESC");
                    if (dt.Rows.Count > 0)
                    {
                        string cutGroup = dt.Rows[0]["cutGroup"].ToString().ToString().Split('=')[1];
                        string resultID = dt.Rows[0]["id"].ToString().ToString();
                        string[] _lenght = cutGroup.Split('+');
                        List<string> sqlList = new List<string>
                        {
                            $"UPDATE [PM.AiResult] SET num=num+{mNum},numBack=numBack+{mNum} WHERE id={resultID}",
                            $"UPDATE [PM.AiSc] SET num=num-{mNum} WHERE mID='{mID}' AND lg={mLength}"
                        };
                        foreach (var _l in _lenght)
                        {
                            string[] l = _l.Split('*');
                            sqlList.Add($"UPDATE [PM.AiJh] SET num=num-{mNum}*{l[1]} WHERE mId='{mID}' AND lg={l[0]}");
                        }
                        sqlHelper.ExcuteSql(sqlList);
                    }
                    else
                    {
                    }
                }
            }
        }

        public void C4()
        {
            jhDt = sqlHelper.GetDataTableFromSql($"SELECT * FROM [PM.AiJh] WHERE mID='{mID}' AND num>0 ORDER BY lg DESC,num DESC");
            scDt = sqlHelper.GetDataTableFromSql($"SELECT * FROM [PM.AiSc] WHERE mID='{mID}' AND num>0 ORDER BY lg ASC");
            if (jhDt.Rows.Count > 0 && scDt.Rows.Count > 0)
            {
                int rank = 2;
                if (jhDt.Rows.Count < 2)
                {
                    rank = jhDt.Rows.Count;
                }
                var cn = new Combination(jhDt.Rows.Count, rank);
                List<double> length = new List<double>();
                foreach (DataRow item in jhDt.Rows)
                {
                    length.Add(double.Parse(item["lg"].ToString()));
                }
                List<double[]> r = new List<double[]>();
                foreach (var row in cn.GetRows())
                {
                    //将组合映射到对象中，循环获取组合的每一个对象
                    List<double> l = new List<double>();
                    foreach (var thing in Combination.Permute(row, length.ToArray()))
                    {
                        l.Add(thing);
                    }
                    r.Add(l.ToArray());
                }
            }
        }

        /// <summary>
        /// 统计计划完成率和非计划率
        /// </summary>
        /// <param name="sqlHelper"> </param>
        /// <param name="mId">       </param>
        /// <returns> </returns>
        public static SumResult Sum(SqlHelper sqlHelper, string mId)
        {
            DataTable dt = sqlHelper.GetDataTableFromSql($"SELECT ISNULL(SUM(num),0) NUM FROM [PM.AiJh] WHERE mId='{mId}' AND num>0 UNION ALL SELECT ABS(ISNULL(SUM(num),0)) NUM FROM[PM.AiJh] WHERE mId = '{mId}' AND num < 0 UNION ALL SELECT SUM(numBack) FROM[PM.AiJh] NUM WHERE mId = '{mId}'UNION ALL SELECT ABS(ISNULL(SUM(realNum), 0)) NUM FROM[PM.AiJh] WHERE mId = '{mId}' AND numBack > 0");
            int.TryParse(dt.Rows[0]["NUM"].ToString(), out var qzs);
            int.TryParse(dt.Rows[1]["NUM"].ToString(), out var fzs);
            int.TryParse(dt.Rows[2]["NUM"].ToString(), out var allzs);
            int.TryParse(dt.Rows[3]["NUM"].ToString(), out var realzs);
            dt = sqlHelper.GetDataTableFromSql($"SELECT cutGroup,numBack FROM [PM.AiResult] WHERE mID = '{mId}';");
            double allLength = 0;
            double noUseLength = 0;
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    int.TryParse(row["numBack"].ToString(), out var numBack);
                    var g = row["cutGroup"].ToString().Split('=')[1].Split('+');
                    foreach (var item in g)
                    {
                        var l = item.Split('*');
                        double.TryParse(l[0], out var lg);
                        int.TryParse(l[1], out var n);
                        allLength += lg * n * numBack;
                        if (lg < 6)
                        {
                            noUseLength += lg * n * numBack;
                        }
                    }
                }
            }
            SumResult sumResult = new SumResult()
            {
                Mid = mId,
                JhNoPlanPercent = 0,
                JhPlanPercent = 0,
                RealPercent = 0,
                AllLength = allLength,
                NoUseLength = noUseLength,
                CutGroupCount = dt.Rows.Count
            };
            if (allzs > 0)
            {
                sumResult.JhPlanPercent = (((allzs - qzs) * 1.000) / (allzs * (1.000))) * 100.000;
                sumResult.JhNoPlanPercent = ((fzs * 1.000) / (allzs * 1.000)) * 100.000;
                sumResult.RealPercent = ((realzs * 1.000) / (allzs * 1.000)) * 100.000;
            }
            string sql = $@"IF NOT EXISTS (SELECT mid FROM [PM.AiResultSum] WHERE mid = '{sumResult.Mid}')
    INSERT INTO [PM.AiResultSum]
    (
        mid,
        JhPlanPercent,
        JhNoPlanPercent,
        RealPercent,
        NoUsePercent,
        AllLength,
        NoUseLength,
        CutGroupCount
    )
    VALUES
    ('{sumResult.Mid}', {sumResult.JhPlanPercent}, {sumResult.JhNoPlanPercent}, {sumResult.RealPercent}, {sumResult.NoUsePercent}, {sumResult.AllLength}, {sumResult.NoUseLength}, {sumResult.CutGroupCount});
ELSE
    UPDATE [PM.AiResultSum]
    SET JhPlanPercent = {sumResult.JhPlanPercent},
        JhNoPlanPercent = {sumResult.JhNoPlanPercent},
        RealPercent = {sumResult.RealPercent},
        NoUsePercent = {sumResult.NoUsePercent},
        AllLength = {sumResult.AllLength},
        NoUseLength = {sumResult.NoUseLength},
        CutGroupCount = {sumResult.CutGroupCount}
    WHERE mid = '{sumResult.Mid}'";
            sqlHelper.ExcuteSql(sql);
            return sumResult;
        }
    }

    public class SumResult
    {
        /// <summary>
        /// 计划完成率
        /// </summary>
        public double JhPlanPercent { get; set; }

        /// <summary>
        /// 非计划率
        /// </summary>
        public double JhNoPlanPercent { get; set; }

        /// <summary>
        /// 当前进度
        /// </summary>
        public double RealPercent { get; set; }

        /// <summary>
        /// 废钢率
        /// </summary>
        public double NoUsePercent
        {
            get
            {
                if (AllLength > 0)
                {
                    return (NoUseLength / AllLength) * 100;
                }
                return 0;
            }
        }

        /// <summary>
        /// 总长度
        /// </summary>
        public double AllLength { get; set; }

        /// <summary>
        /// 废钢总长
        /// </summary>
        public double NoUseLength { get; set; }

        public int CutGroupCount { get; set; } = 0;

        public string Mid { get; set; }
    }
}